<template>
  <div class="order-detail">
    <el-container>
      <el-main>
        <!-- 页面标题 -->
        <div class="page-header">
          <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
          <h1 class="page-title">订单详情</h1>
        </div>

        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>

        <div v-else-if="!order" class="empty-container">
          <el-empty description="订单不存在" />
        </div>

        <div v-else class="order-detail-content">
          <!-- 订单状态 -->
          <el-card class="status-card">
            <template #header>
              <div class="card-header">
                <span>订单状态</span>
                <el-tag :type="getStatusType((order as any).status) as any" size="large">
                  {{ getStatusText((order as any).status) }}
                </el-tag>
              </div>
            </template>
            <div class="status-timeline">
              <el-timeline>
                <el-timeline-item
                  v-for="(activity, index) in getStatusTimeline((order as any).status)"
                  :key="index"
                  :timestamp="activity.timestamp"
                  :type="activity.type as any"
                >
                  {{ activity.content }}
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-card>

          <!-- 订单信息 -->
          <el-card class="info-card">
            <template #header>
              <span>订单信息</span>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单号">
                {{ (order as any)?.orderSn || order?.orderNumber }}
              </el-descriptions-item>
              <el-descriptions-item label="下单时间">
                {{ formatDate((order as any)?.createdAt || order?.createdAt) }}
              </el-descriptions-item>
              <el-descriptions-item label="支付方式">
                {{ order?.paymentMethod || '在线支付' }}
              </el-descriptions-item>
              <el-descriptions-item label="订单金额">
                <span class="amount">¥{{ (order as any)?.totalAmount || order?.productTotal }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 收货信息 -->
          <el-card class="address-card">
            <template #header>
              <span>收货信息</span>
            </template>
            <div class="address-info">
              <p><strong>收货人：</strong>{{ (order as any).receiverName || '未知' }}</p>
              <p><strong>联系电话：</strong>{{ (order as any).receiverPhone || '未知' }}</p>
              <p><strong>收货地址：</strong>{{ (order as any).receiverAddress || '未知' }}</p>
            </div>
          </el-card>

          <!-- 订单备注 -->
          <el-card v-if="order?.remark" class="remark-card">
            <template #header>
              <span>订单备注</span>
            </template>
            <div class="remark-info">
              <el-tag type="info" size="large" class="remark-tag">
                <i class="el-icon-edit"></i>
                {{ order?.remark }}
              </el-tag>
            </div>
          </el-card>

          <!-- 测试备注显示（开发环境） -->
          <el-card v-if="!order?.remark && isDev" class="remark-card test-remark">
            <template #header>
              <span>测试备注（开发环境）</span>
            </template>
            <div class="remark-info">
              <el-tag type="warning" size="large" class="remark-tag">
                <i class="el-icon-edit"></i>
                这是一个测试备注，用于验证备注显示功能
              </el-tag>
            </div>
          </el-card>

          <!-- 商品信息 -->
          <el-card class="products-card">
            <template #header>
              <span>商品信息</span>
            </template>
            <div class="products-list">
              <div v-for="item in (order as any)?.orderItems || (order as any)?.items || []" :key="item.itemId" class="product-item">
                <el-image
                  :src="item.productImage"
                  :alt="item.productName"
                  class="product-image"
                  fit="cover"
                />
                <div class="product-info">
                  <h4 class="product-name">{{ item.productName }}</h4>
                  <p class="product-spec">SKU：{{ item.productSku }}</p>
                  <p class="product-price">¥{{ item.productPrice }}</p>
                </div>
                <div class="product-quantity">
                  <span>数量：{{ item.quantity }}</span>
                  <span class="subtotal">小计：¥{{ item.totalPrice }}</span>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 订单操作 -->
          <el-card class="actions-card">
            <template #header>
              <span>订单操作</span>
            </template>
            <div class="order-actions">
              <el-button
                v-if="(order as any).status === 0"
                type="primary"
                size="large"
                @click="payOrder"
              >
                立即付款
              </el-button>
              <el-button
                v-if="(order as any).status === 2"
                type="success"
                size="large"
                @click="confirmReceive"
              >
                确认收货
              </el-button>
              <el-button v-if="(order as any).status === 0 || (order as any).status === 1" size="large" @click="cancelOrder">
                取消订单
              </el-button>
              <el-button 
                v-if="canReviewOrder((order as any).status) && hasReviewableItems()" 
                type="primary" 
                size="large"
                @click="openReviewModal"
              >
                评价商品
              </el-button>
              <el-tooltip 
                v-else-if="(order as any).status !== 3"
                content="只有已完成的订单才能评价"
                placement="top"
              >
                <el-button type="primary" size="large" disabled>
                  评价订单
                </el-button>
              </el-tooltip>
              <el-button size="large" @click="downloadInvoice"> 下载发票 </el-button>
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>

    <!-- 评价弹窗 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="商品评价"
      width="600px"
      :before-close="handleCloseReviewDialog"
    >
      <div class="review-form">
        <!-- 商品评价 -->
        <div class="order-items-review">
          <h4>商品评价</h4>
          <p v-if="reviewForm.length === 0" style="color: #999;">暂无商品数据</p>
          <div v-for="(item, index) in reviewForm" :key="item.itemId" class="review-item">
            <div class="item-info">
              <el-image
                :src="item.productImage"
                :alt="item.productName"
                class="item-image"
                fit="cover"
              />
              <div class="item-details">
                <p class="item-name">{{ item.productName }}</p>
                <p class="item-spec">{{ item.productSpec }}</p>
              </div>
            </div>
            <div class="rating-section">
              <p>商品评分：</p>
              <el-rate
                v-model="reviewForm[index].rating"
                :max="5"
                show-text
                :texts="['极差', '失望', '一般', '满意', '惊喜']"
              />
            </div>
            <div class="comment-section">
              <p>商品评价：</p>
              <el-input
                v-model="reviewForm[index].comment"
                type="textarea"
                :rows="3"
                placeholder="请分享您对这件商品的使用体验..."
                maxlength="500"
                show-word-limit
              />
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReviews" :loading="submittingReview">
            提交评价
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderService, stockService, productService, reviewService } from '@/api'
import { useAuthStore } from '@/stores/auth'
import type { Order } from '@/types/order'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const order = ref<Order | null>(null)
const loading = ref(false)
const reviewDialogVisible = ref(false)
const submittingReview = ref(false)
const reviewForm = ref<any[]>([])
// 环境变量检查
const isDev = import.meta.env?.DEV || false

// 方法
const fetchOrderDetail = async () => {
  const orderId = route.params.id
  if (!orderId) return

  loading.value = true
  try {
    // 【重要】调用真实的订单详情API，获取最新的订单状态和信息
    // ⚠️ 请勿删除此逻辑，否则会显示错误的订单信息
    const response = await orderService.getOrderDetail(Number(orderId))
    order.value = response.data.data
    
    console.log('订单详情加载成功:', {
      orderId: (order.value as any).orderId,
      orderSn: (order.value as any).orderSn,
      status: (order.value as any).status,
      statusDesc: getStatusText((order.value as any).status?.toString() || '0')
    })
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
    
    // 如果API调用失败，跳转回订单列表
    setTimeout(() => {
      router.push('/orders')
    }, 2000)
  } finally {
    loading.value = false
  }
}

const getStatusType = (status: string | number) => {
  const statusCode = typeof status === 'number' ? status : parseInt(status || '0')
  const statusMap: Record<number, string> = {
    0: 'warning',  // 待付款
    1: 'info',     // 待发货 
    2: 'primary',  // 运输中
    3: 'success',  // 已完成
    4: 'danger',   // 已取消
    5: 'warning',  // 申请退货
    6: 'info',     // 已退货
  }
  return statusMap[statusCode] || 'info'
}

const getStatusText = (status: string | number) => {
  const statusCode = typeof status === 'number' ? status : parseInt(status || '0')
  const statusMap: Record<number, string> = {
    0: '待付款',
    1: '待发货',
    2: '运输中', 
    3: '已完成',
    4: '已取消',
    5: '申请退货',
    6: '已退货',
  }
  return statusMap[statusCode] || '未知状态'
}

const getStatusTimeline = (status: string | number) => {
  const statusCode = typeof status === 'number' ? status : parseInt(status || '0')
  const timeline = [
    {
      content: '订单已创建',
      timestamp: (order.value as any)?.createdAt ? formatDate((order.value as any).createdAt) : '未知时间',
      type: 'primary',
    },
  ]

  // 0: 待付款状态
  if (statusCode >= 0 && statusCode !== 4) {
    timeline.push({
      content: '等待付款',
      timestamp: (order.value as any)?.createdAt ? formatDate((order.value as any).createdAt) : '未知时间',
      type: 'warning',
    })
  }

  // 1: 待发货 (支付成功)
  if (statusCode >= 1 && statusCode !== 4) {
    timeline.push({
      content: '付款成功',
      timestamp: (order.value as any)?.updatedAt ? formatDate((order.value as any).updatedAt) : '未知时间',
      type: 'success',
    })
  }

  // 2: 运输中 (已发货)
  if (statusCode >= 2 && statusCode !== 4) {
    timeline.push({
      content: '商品已发货',
      timestamp: (order.value as any)?.updatedAt ? formatDate((order.value as any).updatedAt) : '未知时间',
      type: 'info',
    })
  }

  // 3: 已完成
  if (statusCode === 3) {
    timeline.push({
      content: '订单已完成',
      timestamp: (order.value as any)?.updatedAt ? formatDate((order.value as any).updatedAt) : '未知时间',
      type: 'success',
    })
  }

  // 4: 已取消
  if (statusCode === 4) {
    timeline.push({
      content: '订单已取消',
      timestamp: (order.value as any)?.updatedAt ? formatDate((order.value as any).updatedAt) : '未知时间',
      type: 'danger',
    })
  }

  return timeline
}

const formatDate = (date: Date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
}

const payOrder = () => {
  router.push({
    path: '/payment',
    query: { orderId: order.value?.orderId }
  })
}

const confirmReceive = async () => {
  try {
    await ElMessageBox.confirm('确认已收到商品？', '确认收货', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 调用确认收货API
    await orderService.confirmReceipt(Number(order.value?.orderId))
    ElMessage.success('确认收货成功')
    // 刷新订单详情
    fetchOrderDetail()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error(error.message || '确认收货失败')
    }
  }
}

const cancelOrder = async () => {
  try {
    await ElMessageBox.confirm('确认取消订单？', '取消订单', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 调用取消订单API（后端已集成库存恢复逻辑）
    try {
      const cancelResult = await orderService.cancelOrder(Number(order.value?.orderId))
      
      if (cancelResult && cancelResult.status === 200) {
        ElMessage.success('订单取消成功')
        // 更新本地订单状态
        ;(order.value as any).status = 4
        // 刷新订单详情
        await fetchOrderDetail()
      } else {
        ElMessage.error('取消订单失败')
      }
    } catch (e) {
      console.error('调用取消订单API失败:', e)
      ElMessage.error('取消订单失败，请重试')
      return
    }

    ElMessage.success('订单已取消')
    // 立即更新本地状态为“已取消”，优化交互
    try {
      ;(order.value as any).status = 4
    } catch {}
    // 刷新订单详情，确保与后端同步
    fetchOrderDetail()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error(error.message || '取消订单失败')
    }
  }
}

const openReviewModal = async () => {
  // 检查用户认证状态
  if (!authStore.isAuthenticated) {
    ElMessage.error('请先登录')
    return
  }

  console.log('打开评价弹窗，用户信息:', {
    userId: authStore.user?.id,
    username: authStore.user?.username,
    isAuthenticated: authStore.isAuthenticated
  })

  // 初始化评论表单数据
  // API返回的数据结构中商品列表字段名为orderItems
  const orderItems = (order.value as any)?.orderItems || (order.value as any)?.items
  
  if (order.value && orderItems && Array.isArray(orderItems)) {
    // 检查每个商品是否已经评价过
    const reviewableItems = []
    
    for (const item of orderItems) {
      try {
        // 检查该商品是否已经评价过
        const hasReview = await checkItemReviewStatus(item.itemId)
        if (!hasReview) {
          reviewableItems.push({
            itemId: item.itemId,
            productName: item.productName,
            productImage: item.productImage,
            productSpec: item.productSku || item.productSpec || `${item.productName} 规格`,
            rating: 5,
            comment: ''
          })
        }
      } catch (error) {
        console.error('检查商品评价状态失败:', error)
        // 如果检查失败，默认允许评价
        reviewableItems.push({
          itemId: item.itemId,
          productName: item.productName,
          productImage: item.productImage,
          productSpec: item.productSku || item.productSpec || `${item.productName} 规格`,
          rating: 5,
          comment: ''
        })
      }
    }
    
    if (reviewableItems.length === 0) {
      ElMessage.info('该订单的所有商品都已经评价过了')
      return
    }
    
    reviewForm.value = reviewableItems
  } else {
    ElMessage.error('订单商品数据加载失败，请刷新页面重试')
    return
  }
  
  reviewDialogVisible.value = true
}

const handleCloseReviewDialog = () => {
  reviewDialogVisible.value = false
  // 重置表单数据
  reviewForm.value = []
}

const submitReviews = async () => {
  if (!reviewForm.value || reviewForm.value.length === 0) {
    ElMessage.error('评论表单数据不完整')
    return
  }

  // 检查用户认证状态
  if (!authStore.isAuthenticated) {
    ElMessage.error('请先登录')
    return
  }

  console.log('当前用户信息:', {
    userId: authStore.user?.id,
    username: authStore.user?.username,
    isAuthenticated: authStore.isAuthenticated,
    token: authStore.token
  })

  // 验证所有商品都有评分
  for (const item of reviewForm.value) {
    if (!item.rating || item.rating < 1 || item.rating > 5) {
      ElMessage.error('请为所有商品评分（1-5分）')
      return
    }
  }

  submittingReview.value = true
  
  try {
    console.log('当前订单状态:', (order.value as any)?.status)
    console.log('订单状态描述:', getStatusText((order.value as any)?.status))
    console.log('准备提交的商品评价数据:', reviewForm.value)
    
    // 为每个订单项提交评价
    const reviewPromises = reviewForm.value.map((item: any) => {
      const reviewData = {
        orderItemId: item.itemId,
        rating: item.rating,
        comment: item.comment || ''
      }
      console.log('提交单个评价:', reviewData)
      console.log('订单信息:', {
        orderId: (order.value as any)?.orderId,
        orderUserId: (order.value as any)?.userId,
        currentUserId: authStore.user?.id,
        orderStatus: (order.value as any)?.status
      })
      return reviewService.addReview(reviewData)
    })

    await Promise.all(reviewPromises)
    
    ElMessage.success('商品评价提交成功！')
    reviewDialogVisible.value = false
    
    // 刷新订单详情
    fetchOrderDetail()
  } catch (error: any) {
    console.error('提交评价失败:', error)
    
    // 优化错误提示，让用户更容易理解
    const errorMsg = error.response?.data?.message || error.response?.data?.msg || '评价提交失败'
    
    if (errorMsg.includes('无法评价该商品')) {
      // 检查是否是因为已经评价过
      if (error.response?.data?.code === -1) {
        ElMessage.warning('该商品已经评价过了，不能重复评价')
      } else {
        ElMessage.warning('该商品暂时无法评价，请稍后再试')
      }
    } else if (errorMsg.includes('已经评价过')) {
      ElMessage.warning('该商品已经评价过了，不能重复评价')
    } else if (errorMsg.includes('订单状态')) {
      ElMessage.warning('订单状态不符合评价条件，请确认订单已完成')
    } else {
      ElMessage.error(errorMsg)
    }
  } finally {
    submittingReview.value = false
  }
}

const downloadInvoice = () => {
  ElMessage.info('发票下载功能开发中')
}

// 检查商品是否已经评价过
const checkItemReviewStatus = async (orderItemId: number): Promise<boolean> => {
  try {
    // 调用后端API检查商品是否已经评价过
    const response = await reviewService.checkReviewExists(orderItemId)
    console.log('检查商品评价状态响应:', response)
    // 如果返回true，说明已经评价过
    return response.data.data === true
  } catch (error) {
    console.error('检查商品评价状态失败:', error)
    // 如果检查失败，默认返回false（允许评价）
    return false
  }
}

// 检查订单是否可以评价
const canReviewOrder = (status: number) => {
  return status === 3 // 只有已完成的订单才能评价
}

// 检查是否有可以评价的商品
const hasReviewableItems = (): boolean => {
  if (!order.value) return false
  
  const orderItems = (order.value as any)?.orderItems || (order.value as any)?.items
  if (!orderItems || !Array.isArray(orderItems)) return false
  
  // 暂时返回true，让用户尝试评价
  // 如果已经评价过，后端会返回相应的错误信息
  return true
}

const goBack = () => {
  router.back()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail {
  min-height: calc(100vh - 64px);
  background-color: #f8fafc;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.loading-container {
  padding: 40px 0;
}

.empty-container {
  padding: 60px 0;
}

.order-detail-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.status-card,
.info-card,
.address-card,
.products-card,
.actions-card {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-timeline {
  padding: 20px 0;
}

.address-info p {
  margin: 8px 0;
  line-height: 1.6;
}

.remark-card {
  margin-bottom: 20px;
}

.remark-info {
  padding: 16px 0;
}

.remark-tag {
  font-size: 16px;
  padding: 12px 20px;
  border-radius: 8px;
  background: #f0f9ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.remark-tag i {
  margin-right: 8px;
}

.test-remark {
  border-left: 4px solid #e6a23c;
}

.test-remark .remark-tag {
  background: #fdf6ec;
  border-color: #f5dab1;
  color: #b88230;
}

.products-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.product-item {
  display: flex;
  gap: 16px;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  background: #fafafa;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 8px 0;
}

.product-spec {
  font-size: 14px;
  color: #606266;
  margin: 0 0 8px 0;
}

.product-price {
  font-size: 16px;
  font-weight: 600;
  color: #e6a23c;
  margin: 0;
}

.product-quantity {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-between;
  min-width: 120px;
}

.subtotal {
  font-weight: 600;
  color: #e6a23c;
}

.amount {
  font-size: 18px;
  font-weight: 600;
  color: #e6a23c;
}

.order-actions {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

/* 评论弹窗样式 */
.review-form {
  padding: 20px 0;
}

.review-form {
  max-height: 70vh;
  overflow-y: auto;
}

.order-items-review h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
}

.review-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  background: #fafafa;
}

.review-item:last-child {
  margin-bottom: 0;
}

.item-info {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  object-fit: cover;
}

.item-details {
  flex: 1;
}

.item-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 4px 0;
}

.item-spec {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

.rating-section {
  margin-bottom: 16px;
}

.rating-section p {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.comment-section p {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .product-item {
    flex-direction: column;
    gap: 12px;
  }

  .product-image {
    width: 100%;
    height: 200px;
  }

  .product-quantity {
    align-items: flex-start;
    gap: 8px;
  }

  .order-actions {
    flex-direction: column;
  }
}
</style>
